package server

import (
	"fmt"
	"server5/Interface"
	"server5/protobuf"
	"server5/utils"
)

var MsgManager *MsgManage = nil

type MsgManage struct {
	Apis         map[protobuf.MsgType]Interface.IRouter
	TaskQueue    []chan Interface.IRequest
	WorkPoolSize uint32
}

func GetMsgManager() *MsgManage {
	if MsgManager == nil {
		MsgManager = &MsgManage{
			Apis:         make(map[protobuf.MsgType]Interface.IRouter),
			TaskQueue:    make([]chan Interface.IRequest, utils.GlobalObject.WorkerPoolSize),
			WorkPoolSize: utils.GlobalObject.WorkerPoolSize,
		}
	}
	return MsgManager
}

func (m *MsgManage) DealMsg(request Interface.IRequest) {
	handler, ok := m.Apis[request.GetMsgType()]
	if ok {
		handler.Func(request)
	} else {
		//Debug
		fmt.Printf("MsgManage::DealMsg 没有为%v消息类型注册处理方法", request.GetMsgType())
	}
}

func (m *MsgManage) AddRouter(msgType protobuf.MsgType, router Interface.IRouter) {
	if _, ok := m.Apis[msgType]; ok {
		fmt.Printf("MsgManage::AddRouter %v消息类型已经注册过处理方法", msgType)
	}
	m.Apis[msgType] = router
}

func (m *MsgManage) StartWorkerPool() {
	for i := uint32(0); i < m.WorkPoolSize; i++ {
		m.TaskQueue[i] = make(chan Interface.IRequest, utils.GlobalObject.MaxWorkerTaskLen)
		go m.StartOneWorker(i, m.TaskQueue[i])
	}
}

func (m *MsgManage) StartOneWorker(workerId uint32, taskQueue chan Interface.IRequest) {
	for {
		select {
		case request := <-taskQueue:
			m.DealMsg(request)
		}
	}
}

func (m *MsgManage) SendMsgToTaskQueue(request Interface.IRequest) {
	workerId := request.GetConnection().GetConnID() % m.WorkPoolSize
	m.TaskQueue[workerId] <- request
}
